package protocol

import (
	"encoding/binary"
	"servermg/log"
)

const (
	TYPE_QE1      = 1
	QE1HeadLength = 18 //QE 包的头长度
)

type BoyaaPacket struct {
	Type   int32
	data   [2048]byte
	cmd    int32
	length int32
	pos    int32
}

func (packet *BoyaaPacket) writeByte(pos int32, c byte) {
	packet.data[pos] = c
}

func (packet *BoyaaPacket) writeShort(pos int32, x int16) {
	binary.BigEndian.PutUint16(packet.data[pos:pos+2], uint16(x))
}

func (packet *BoyaaPacket) writeInt(pos int32, x int32) {
	binary.BigEndian.PutUint32(packet.data[pos:pos+4], uint32(x))
}

func (packet *BoyaaPacket) writeInt64(pos int32, x int64) {
	binary.BigEndian.PutUint64(packet.data[pos:pos+8], uint64(x))
}

func (packet *BoyaaPacket) readByte(pos int32) byte {
	return packet.data[pos]
}

func (packet *BoyaaPacket) readShort(pos int32) int16 {
	x := binary.BigEndian.Uint16(packet.data[pos : pos+2])
	return int16(x)
}

func (packet *BoyaaPacket) readInt(pos int32) int32 {
	x := binary.BigEndian.Uint32(packet.data[pos : pos+4])
	return int32(x)
}

func (packet *BoyaaPacket) readInt64(pos int32) int64 {
	x := binary.BigEndian.Uint64(packet.data[pos : pos+8])
	return int64(x)
}

func (packet *BoyaaPacket) WriteBeginQE1(cmd int32) {
	packet.writeByte(4, 'B') //flag[2]
	packet.writeByte(5, 'Y')
	packet.writeShort(6, 0)  //version
	packet.writeInt(8, cmd)  //cmd
	packet.writeShort(12, 0) //gameid
	packet.writeShort(14, 0) //regionid
	packet.writeByte(16, 0)  //deviceid
	packet.writeByte(17, 0)  //code

	packet.pos = 18
	packet.cmd = cmd
}

func (packet *BoyaaPacket) WriteEnd() {
	packet.length = packet.pos - 4
	packet.writeInt(0, packet.length)
}

func (packet *BoyaaPacket) GetCmd() int32 {
	return packet.cmd
}

func (packet *BoyaaPacket) WriteByte(x byte) {
	packet.writeByte(packet.pos, x)
	packet.pos += 1
}

func (packet *BoyaaPacket) WriteShort(x int16) {
	packet.writeShort(packet.pos, x)
	packet.pos += 2
}

func (packet *BoyaaPacket) WriteInt(x int32) {
	packet.writeInt(packet.pos, x)
	packet.pos += 4
}

func (packet *BoyaaPacket) WriteInt64(x int64) {
	packet.writeInt64(packet.pos, x)
	packet.pos += 8
}

func (packet *BoyaaPacket) ReadByte() byte {
	x := packet.readByte(packet.pos)
	packet.pos += 1
	return x
}
func (packet *BoyaaPacket) ReadShort() int16 {
	x := packet.readShort(packet.pos)
	packet.pos += 2
	return x
}

func (packet *BoyaaPacket) ReadInt() int32 {
	x := packet.readInt(packet.pos)
	packet.pos += 4
	return x
}

func (packet *BoyaaPacket) ReadInt64() int64 {
	x := packet.readInt64(packet.pos)
	packet.pos += 8
	return x
}

func (packet *BoyaaPacket) Data() []byte {
	return packet.data[0 : packet.length+4]
}

func (packet *BoyaaPacket) Packet(buf []byte) {
	length := copy(packet.data[0:len(buf)], buf)
	packet.length = packet.readInt(0)
	packet.cmd = packet.readInt(8)
	if length < int(packet.length+4) {

	}
	packet.pos = 18
	log.Debug("packet cmd:[%x],len:[%d],read len[%d] \n", packet.cmd, packet.length, length)
}
